from flask import Flask, render_template, jsonify, request
import requests
import threading
import time
import json
import os

app = Flask(__name__)

# 配置文件路径
CONFIG_FILE = 'config.json'

# 默认配置
DEFAULT_CONFIG = {
    "services": [
        {
            "id": 1,
            "name": "示例服务",
            "address": "172.100.2.147:8888",
            "status": "未知",
            "remark": "示例备注信息",
            "last_check": "",
            "status_log": "其他信息",
            "owner": ""
        },
        {
            "id": 2,
            "name": "Web服务器",
            "address": "172.100.2.147:8091",
            "status": "未知",
            "remark": "Apache服务器",
            "last_check": "",
            "status_log": "HTTP服务",
            "owner": ""
        },
        {
            "id": 3,
            "name": "数据库服务",
            "address": "192.168.1.101:3306",
            "status": "未知",
            "remark": "MySQL数据库",
            "last_check": "",
            "status_log": "数据库",
            "owner": ""
        },
        {
            "id": 4,
            "name": "缓存服务",
            "address": "192.168.1.102:6379",
            "status": "未知",
            "remark": "Redis缓存",
            "last_check": "",
            "status_log": "内存数据库",
            "owner": ""
        }
    ]
}

# 读取配置文件
def load_config():
    if os.path.exists(CONFIG_FILE):
        with open(CONFIG_FILE, 'r', encoding='utf-8') as f:
            return json.load(f)
    else:
        # 如果配置文件不存在，创建默认配置
        save_config(DEFAULT_CONFIG)
        return DEFAULT_CONFIG

# 保存配置文件
def save_config(config):
    with open(CONFIG_FILE, 'w', encoding='utf-8') as f:
        json.dump(config, f, ensure_ascii=False, indent=4)

# 检查服务状态
def check_service_status(address):
    try:
        # 检查是否为HTTP或HTTPS地址
        if address.startswith('http://') or address.startswith('https://'):
            # 直接使用提供的URL进行HTTP请求
            response = requests.get(address, timeout=5)
            status_log = f"HTTP {response.status_code}"
            if response.status_code == 200:
                return "正常", "连接成功"  # 统一正常状态日志为"连接成功"
            else:
                return "异常", status_log
        elif ':' in address:
            # 分离主机和端口
            host, port = address.split(':')
            port = int(port)
            # 尝试连接到指定端口
            import socket
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.settimeout(5)
            result = sock.connect_ex((host, port))
            sock.close()
            if result == 0:
                return "正常", "连接成功"  # 统一正常状态日志为"连接成功"
            else:
                return "异常", "连接失败"
        else:
            # 如果没有指定端口，使用HTTP请求检查
            url = f"http://{address}"
            response = requests.get(url, timeout=5)
            status_log = f"HTTP {response.status_code}"
            if response.status_code == 200:
                return "正常", "连接成功"  # 统一正常状态日志为"连接成功"
            elif response.status_code == 404:
                return "异常", status_log
            elif response.status_code == 500:
                return "异常", status_log
            else:
                return "异常", status_log
    except Exception as e:
        return "异常", str(e)

# 定期检查所有服务状态
def monitor_services():
    while True:
        config = load_config()
        for service in config['services']:
            status, status_log = check_service_status(service['address'])
            service['status'] = status
            service['status_log'] = status_log
            service['last_check'] = time.strftime('%Y-%m-%d %H:%M:%S')
        
        save_config(config)
        # 每隔60秒检查一次
        time.sleep(60)

# 启动监控线程
monitor_thread = threading.Thread(target=monitor_services, daemon=True)
monitor_thread.start()

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/api/services')
def get_services():
    config = load_config()
    return jsonify(config['services'])

@app.route('/api/check/<int:service_id>')
def check_service(service_id):
    config = load_config()
    for service in config['services']:
        if service['id'] == service_id:
            status, status_log = check_service_status(service['address'])
            service['status'] = status
            service['status_log'] = status_log
            service['last_check'] = time.strftime('%Y-%m-%d %H:%M:%S')
            save_config(config)
            return jsonify({"status": status, "status_log": status_log})
    return jsonify({"error": "服务未找到"}), 404

# 添加批量检查所有服务的API端点
@app.route('/api/check-all')
def check_all_services():
    config = load_config()
    for service in config['services']:
        status, status_log = check_service_status(service['address'])
        service['status'] = status
        service['status_log'] = status_log
        service['last_check'] = time.strftime('%Y-%m-%d %H:%M:%S')
    
    save_config(config)
    return jsonify({"status": "success", "message": "所有服务检查完成"})

# 添加新服务的API端点
@app.route('/api/services', methods=['POST'])
def add_service():
    config = load_config()
    
    # 获取新的ID
    new_id = max([s['id'] for s in config['services']] or [0]) + 1
    
    # 获取请求数据
    data = request.get_json()
    
    # 创建新服务条目
    new_service = {
        "id": new_id,
        "name": data.get('name', ''),
        "address": data.get('address', ''),
        "status": "未知",
        "remark": data.get('remark', ''),
        "last_check": "",
        "status_log": data.get('status_log', ''),
        "owner": data.get('owner', '')
    }
    
    # 添加到服务列表
    config['services'].append(new_service)
    
    # 保存配置
    save_config(config)
    
    return jsonify({"message": "服务添加成功", "id": new_id})

# 添加编辑服务的API端点
@app.route('/api/services/<int:service_id>', methods=['PUT'])
def edit_service(service_id):
    config = load_config()
    
    # 查找要编辑的服务
    service = next((s for s in config['services'] if s['id'] == service_id), None)
    if not service:
        return jsonify({"error": "服务未找到"}), 404
    
    # 获取请求数据
    data = request.get_json()
    
    # 更新服务信息
    service['name'] = data.get('name', service['name'])
    service['address'] = data.get('address', service['address'])
    service['remark'] = data.get('remark', service['remark'])
    service['status_log'] = data.get('status_log', service['status_log'])
    service['owner'] = data.get('owner', service['owner'])
    
    # 保存配置
    save_config(config)
    
    return jsonify({"message": "服务更新成功"})

# 添加删除服务的API端点
@app.route('/api/services/<int:service_id>', methods=['DELETE'])
def delete_service(service_id):
    config = load_config()
    
    # 查找要删除的服务
    service_index = next((i for i, s in enumerate(config['services']) if s['id'] == service_id), None)
    if service_index is None:
        return jsonify({"error": "服务未找到"}), 404
    
    # 从服务列表中删除
    deleted_service = config['services'].pop(service_index)
    
    # 保存配置
    save_config(config)
    
    return jsonify({"message": "服务删除成功", "deleted_service": deleted_service})

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)